package com.dage.salesflow.service;

import com.dage.salesflow.constant.SysConstant;
import com.dage.salesflow.constant.YesNoEnum;
import com.dage.salesflow.excel.model.ProductProfileExcel;
import com.dage.salesflow.model.Dict;
import com.dage.salesflow.model.ProductProfile;
import com.dage.salesflow.model.vo.QuerySql;
import com.jfinal.aop.Inject;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import io.jboot.aop.annotation.Bean;
import io.jboot.utils.CacheUtil;

import java.util.ArrayList;
import java.util.List;

@Bean
public class ProductProfileService extends BaseService<ProductProfile, ProductProfileExcel> {

	@Inject
	DictService dictService;

	protected QuerySql listSql(ProductProfile model, boolean order) {
		String select = "SELECT t.*,d0.dic_value unit_str,d1.dic_value spec_str,d2.dic_value type_str,f0.`name` area_id_str";
		String sql = "FROM `product_profile` t"
				+ "\n LEFT JOIN t_dict d0 ON t.unit=d0.id"
				+ "\n LEFT JOIN t_dict d1 ON t.spec=d1.id"
				+ "\n LEFT JOIN t_dict d2 ON t.type=d2.id"
				+ "\n LEFT JOIN t_area f0 ON t.area_id=f0.id"
				+ "\n WHERE t.is_deleted=0";
		List<Object> paras = new ArrayList<>();
		if (StrKit.notBlank(model.getName())) {
			sql += " AND `name` like ?";
			paras.add("%" + model.getName() + "%");
		}
		if (StrKit.notBlank(model.getCode())) {
			sql += " AND `code` = ?";
			paras.add(model.getCode());
		}
		if (model.getExpiryDate() != null) {
			sql += " AND expiry_date=?";
			paras.add(model.getExpiryDate());
		}
		if (model.getIsMedical() != null) {
			sql += " AND is_medical=?";
			paras.add(model.getIsMedical());
		}
		if (model.getIsBasicDrug() != null) {
			sql += " AND is_basic_drug=?";
			paras.add(model.getIsBasicDrug());
		}
		sql += " ORDER BY `create_time` DESC";
		return new QuerySql(select, sql, paras);
	}

	protected void addCache(ProductProfile model) {
		Dict dict = dictService.findById(model.getSpec());
		CacheUtil.put(SysConstant.CACHE_PRODUCT, model.getName() + "_" + dict.getDicValue(), model.getId());
	}

	protected void removeCache(Object id) {
		Record record = Db.findFirst("SELECT pp.`name`,dic_value specname FROM product_profile pp\n" +
				"INNER JOIN t_dict d ON pp.spec=d.id\n" +
				"WHERE pp.id=?", id);
		CacheUtil.remove(SysConstant.CACHE_PRODUCT, record.getStr("name") + "_" + record.getStr("specname"));
	}

	/**
	 * 根据名称和规格查询id
	 */
	public Integer getIdByNameAndSpec(String name, String spec) {
		Integer id = CacheUtil.get(SysConstant.CACHE_PRODUCT, name + "_" + spec);
		if (id == null) {
			String sql = "SELECT pp.id FROM product_profile pp\n" +
					"INNER JOIN t_dict d ON pp.spec=d.id\n" +
					"WHERE pp.`name`=? AND d.dic_value=? AND pp.is_deleted=?";
			id = Db.queryInt(sql, name, spec, YesNoEnum.NO.getValue());
			CacheUtil.put(SysConstant.CACHE_PRODUCT, name + "_" + spec, id);
		}
		return id;
	}
}
